import React, { useState, useEffect } from 'react'
import { useSelector } from 'react-redux'

//引入样式
import classes from './Cart.module.css'
//引入图片（'/scr'下为私有目录，服务器访问不到，用引入形式）
import bagIcon from '../../asset/bag.png'
//引入组件
import CartDetail from './CartDetail/CartDetail'
import CartPay from './CartPay/CartPay'

export default function Cart() {
	const [showDetail, setshowDetail] = useState(false)
	const [showPay, setshowPay] = useState(false)

	const pickedMeals = [...useSelector(state => state.counter.value)]

	let totalNum = 0
	let totalPrice = 0

	pickedMeals.forEach(m => {
		totalNum = totalNum + m.pickedNum
		totalPrice = totalPrice + m.pickedNum * m.price
	})

	const toggleDetail = () => {
		setshowDetail(prevState => !prevState)
	}

	const togglePay = () => {
		setshowPay(prevState => !prevState)
	}

	return (
		<div className={classes.CartContainer}>
			{showDetail && pickedMeals.length !== 0 && <CartDetail />}

			{showPay && pickedMeals.length !== 0 && <CartPay togglePay={togglePay} />}

			<div className={classes.CartWrap} onClick={toggleDetail}>
				<div className={classes.CartImg}>
					<img src={bagIcon} alt="bag" />
					<span
						className={classes.CartCount}
						style={pickedMeals.length === 0 ? { display: 'none' } : {}}
					>
						{totalNum}
					</span>
				</div>
				{pickedMeals.length === 0 ? (
					<p className={classes.CartNoMeals}>未选购商品</p>
				) : (
					<p className={classes.CartTotalPrice}>
						<span>￥</span>
						{totalPrice}
					</p>
				)}
				<button
					className={`${classes.CartSettle} 
								${pickedMeals.length === 0 ? '' : classes.CartEnable}`}
					onClick={togglePay}
				>
					去结算
				</button>
			</div>
		</div>
	)
}
